package com.digua.tank;

import java.awt.*;

/**
 * @author wangdigua
 * @title 子弹、炮弹
 * @date 2020/11/7 12:09 下午
 * @since 1.0.0
 */
public class Bullet {

    public static final int WIDTH = ResourceMgr.bulletD.getWidth();
    public static final int HEIGHT = ResourceMgr.bulletD.getHeight();
    private static final int SPEED = 10 ;
    private TankFrame tankFrame ;

    private Rectangle rectangle = new Rectangle();

    private int x , y;
    //子弹的方向和坦克方向一致
    private Dir dir ;
    //存活状态
    private boolean live  = true;
    private Group group = Group.BAD;
    private static Audio audio =  new Audio("audio/tank_fire.wav") ;

    public Bullet(int x, int y, Dir dir, TankFrame tankFrame,Group group) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.tankFrame = tankFrame;
        this.group = group;
        if (group == Group.GOOD) {
//            audio.player();
        }
        rectangle.x = this.x;
        rectangle.y = this.y;
        rectangle.width = WIDTH;
        rectangle.height = HEIGHT;
    }

    /**
     * 画出子弹
     * @param g
     */
    public void paint(Graphics g) {
        if (!live) {
            tankFrame.bullets.remove(this);
        }
        switch (dir) {
            case LEFT:
                g.drawImage(ResourceMgr.bulletL, x, y, null);
                break;
            case RIGHT:
                g.drawImage(ResourceMgr.bulletR, x, y, null);
                break;
            case UP:
                g.drawImage(ResourceMgr.bulletU, x, y, null);
                break;
            case DOWN:
                g.drawImage(ResourceMgr.bulletD, x, y, null);
                break;
            default:
                break;
        }
        //重画的时候移动
        move();
    }

    //移动过程中做碰撞检查
    private void move() {
        switch (dir) {
            case LEFT:
                x -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
                break;
            case UP:
                y -= SPEED;
                break;
            case DOWN:
                y += SPEED;
                break;
        }
        //碰撞检测
        rectangle.x = this.x;
        rectangle.y = this.y;
        if (x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) {
            live = false;
        }
    }

    //碰撞检查
    public void collideWith(Tank tank) {
        if (this.group == tank.getGroup()) {
            return;
        }
        if (this.rectangle.intersects(tank.rectangle)) {
            tank.die();
            this.die();
            //添加爆炸效果
            tankFrame.explods.add(new Explod(tank.getX(), tank.getY(), tankFrame));
        }

    }

    private void die() {
        this.live = false;
    }

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }
}
